package cn.kgc.spring.dynamic;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

/**
 * @author 课工场
 * @date 2024/2/22
 * @description
 */
public class CgLibProxy {

    private Object target;

    public CgLibProxy(Object target){
        this.target = target;
    }

    // 获取代理对象
    public Object getProxy(){

        Enhancer enhancer = new Enhancer();
        //  设置代理对象的父类
        enhancer.setSuperclass(target.getClass());

        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                System.out.println("-----------开始记录日志-------------");
                //  执行目标方法
                Object invoke = method.invoke(target, objects);

                return invoke;
            }
        };

        // 设置增强的业务
        enhancer.setCallback(invocationHandler);

        Object o = enhancer.create();
        return o;
    }

}
